package com.zs;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zs.bean.Resource;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class PathJson {

    private final static String ROOT_PATH = "/Users/zengshan/Documents/其它/tvbox";
    private final static String shareFilePath = ROOT_PATH + "/share.json";

    //本地仓路径模版
    private final static String localWarehouseFilePath = ROOT_PATH + "/本地仓.json";
    private final static String remotWarehouseFilePath = ROOT_PATH + "/index.json";

    private final static String localWarehouseTemplete = "clan://localhost/tvbox/%s";
    private final static String remoteWarehouseTemplete = "https://gitee.com/jon3/tvbox/raw/master/%s";


    private static List<Resource> parsePath() {
        List<Resource> resources = new ArrayList<>();
        File rootFile = new File(ROOT_PATH);
        File[] files = rootFile.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    try {
                        File curr = file.getCanonicalFile();
                        File[] child = curr.listFiles();
                        if (child != null) {
                            boolean add = false;
                            for (File childFile : child) {
                                if (childFile.isFile() && childFile.getName().endsWith(".json")) {
                                    if (!add) {
                                        String filePath = file.getName() + "/" + childFile.getName();
                                        Resource resource = new Resource().setName(file.getName())
                                                .setPath(String.format(localWarehouseTemplete, filePath))
                                                .setUrl(String.format(remoteWarehouseTemplete, URLUtil.encode(filePath)));
                                        resources.add(resource);
                                        add = true;
                                    }
                                } else {
                                    if (Objects.equals("lives", childFile.getName())) {
                                        FileUtil.del(childFile);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        System.err.println("解析出错：" + e.getMessage());
                    }
                }
            }
        }
        return resources;
    }


    private static List<Resource> parseShareResource(boolean check) {
        List<Resource> reachables = new ArrayList();
        String share = FileUtil.readString(shareFilePath, Charset.defaultCharset());
        JSONObject jsonObject = JSONUtil.parseObj(share);
        JSONArray urls = jsonObject.getJSONArray("urls");
        List<Resource> list = JSONUtil.toList(urls, Resource.class);
        list.forEach(e -> {
            if (check) {
                boolean reachable = checkUrl(e.getName(), e.getUrl());
                if (reachable) {
                    reachables.add(e);
                }
            }else {
                reachables.add(e);
            }
        });
        JSONObject json = new JSONObject();
        json.putOpt("urls", JSONUtil.parseArray(reachables));
        FileWriter writer = new FileWriter(shareFilePath);
        writer.write(JSONUtil.toJsonPrettyStr(json));
        return reachables;
    }


    /**
     * 检测API是否能连通
     */
    public static boolean checkUrl(String name, String urlStirng) {
        try {
            URL url = new java.net.URL(urlStirng);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/4.0");
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(1000);
            connection.connect();
            int code = connection.getResponseCode();
            System.out.println(name + ":" + code);
            List<Integer> reject = Arrays.asList(400, 403, 404, 502);
            if (reject.contains(code)) {//判断状态码
                return false;
            } else {
                return true;
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return true;
        }
    }


    private static void createLocalJson(List<Resource> resources) {
        JSONArray jsonArrayLocal = new JSONArray();
        resources.forEach(resource -> {
            JSONObject local = new JSONObject();
            local.putOpt("name", resource.getName());
            local.putOpt("url", resource.getPath());
            jsonArrayLocal.add(local);
        });
        JSONObject json = new JSONObject();
        json.putOpt("urls", jsonArrayLocal);
        FileWriter writerLocal = new FileWriter(localWarehouseFilePath);
        writerLocal.write(JSONUtil.toJsonPrettyStr(json));
    }

    private static void createIndexJson(List<Resource> resources, List<Resource> shareResource, boolean filter) {
        List<String> name = resources.stream().map(Resource::getName).collect(Collectors.toList());
        shareResource.forEach(item -> {
            if (filter) {
                if (!name.contains(item.getName())) {
                    resources.add(item);
                }
            } else {
                resources.add(item);
            }
        });
        JSONArray jsonArrayRemote = new JSONArray();
        resources.forEach(resource -> {
            JSONObject remote = new JSONObject();
            remote.putOpt("name", resource.getName());
            remote.putOpt("url", resource.getUrl());
            jsonArrayRemote.add(remote);
        });
        JSONObject json = new JSONObject();
        FileWriter writerRemote = new FileWriter(remotWarehouseFilePath);
        json.putOpt("urls", jsonArrayRemote);
        writerRemote.write(JSONUtil.toJsonPrettyStr(json));
    }

    public static void main(String[] args) {
        List<Resource> resources = parsePath();
        List<Resource> shareResource = parseShareResource(false);
        createLocalJson(resources);
        createIndexJson(shareResource, resources,true);
    }

}
